import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:joyagoo/utils/route_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_picker/image_picker.dart';
import '../config/app_colors.dart';
import '../utils/CompressImageManager.dart';
import '../utils/ImageUrlUtil.dart';
import '../utils/JoyBlocUtil.dart';
import 'joy_home_bloc.dart';
import 'joy_search_result_page.dart';

class JoySearchPage extends StatefulWidget {
  const JoySearchPage({super.key});

  @override
  State<JoySearchPage> createState() => _JoySearchPageState();
}

class _JoySearchPageState extends State<JoySearchPage> {
  final TextEditingController _searchController = TextEditingController();
  List<String> _searchHistory = [];
  static const String _searchHistoryKey = 'search_history';
  List searchWordList = [];
  late JoyHomeBloc loginBloc;
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _loadSearchHistory();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  // 加载搜索历史
  Future<void> _loadSearchHistory() async {
    final prefs = await SharedPreferences.getInstance();
    final history = prefs.getStringList(_searchHistoryKey) ?? [];
    setState(() {
      _searchHistory = history;
    });
  }

  // 保存搜索历史
  Future<void> _saveSearchHistory() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(_searchHistoryKey, _searchHistory);
  }

  // 添加搜索记录
  Future<void> _addSearchRecord(String query) async {
    if (query.trim().isEmpty) return;
    
    setState(() {
      // 如果已存在，先移除
      _searchHistory.remove(query);
      // 添加到最前面
      _searchHistory.insert(0, query);
      // 限制历史记录数量
      if (_searchHistory.length > 10) {
        _searchHistory = _searchHistory.take(10).toList();
      }
    });
    
    await _saveSearchHistory();
  }

  // 删除单个搜索记录
  Future<void> _removeSearchRecord(String query) async {
    setState(() {
      _searchHistory.remove(query);
    });
    await _saveSearchHistory();
  }

  // 清空所有搜索记录
  Future<void> _clearAllSearchHistory() async {
    setState(() {
      _searchHistory.clear();
    });
    await _saveSearchHistory();
  }

  // 执行搜索
  void _performSearch(String query) {
    if (query.trim().isEmpty) return;
    
    _addSearchRecord(query);
    JoyNavUtils().to(JoySearchResultPage(searchword: query,));

  }

  // 显示图片选择对话框
  void _showImagePickerDialog() {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (BuildContext context) {
        return Container(
          padding: EdgeInsets.all(20.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 40.w,
                height: 4.h,
                decoration: BoxDecoration(
                  color: AppColors.textHint,
                  borderRadius: BorderRadius.circular(2.r),
                ),
              ),
              SizedBox(height: 20.h),
              Text(
                'Select Image Source',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 20.h),
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        _pickImageFromCamera();
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 16.h),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.3),
                          ),
                        ),
                        child: Column(
                          children: [
                            Icon(
                              Icons.camera_alt,
                              size: 32.sp,
                              color: Colors.white,
                            ),
                            SizedBox(height: 8.h),
                            Text(
                              'Camera',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 16.w),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        _pickImageFromGallery();
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 16.h),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.3),
                          ),
                        ),
                        child: Column(
                          children: [
                            Icon(
                              Icons.photo_library,
                              size: 32.sp,
                              color: Colors.white,
                            ),
                            SizedBox(height: 8.h),
                            Text(
                              'Gallery',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 20.h),
            ],
          ),
        );
      },
    );
  }

  // 从相机选择图片
  Future<void> _pickImageFromCamera() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1800,
        maxHeight: 1800,
        imageQuality: 85,
      );
      if (image != null) {
        _handleSelectedImage(image);
      }
    } catch (e) {
      _showErrorMessage('Camera failed, please try again');
    }
  }

  // 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1800,
        maxHeight: 1800,
        imageQuality: 85,
      );
      if (image != null) {
        _handleSelectedImage(image);
      }
    } catch (e) {
      _showErrorMessage('Image selection failed, please try again');
    }
  }

  // 处理选择的图片
  Future<void> _handleSelectedImage(XFile image) async {



    String originalPath = image.path;
    String directory = originalPath.substring(0, originalPath.lastIndexOf('/'));
    String extension = originalPath.substring(originalPath.lastIndexOf('.'));
    // 生成随机文件名
    String newPath = CompressImageManager.generateRandomImagePath(directory, extension);

    debugPrint("new-Imagepath = $newPath");
    debugPrint("old-Imagepath = $originalPath");
    String newImagePath =  await CompressImageManager.compressImage(originalPath, newPath);
    loginBloc.add(PostUploadFileEvent(context, newImagePath));



    // // 这里可以添加图片搜索的逻辑
    // // 暂时显示提示信息
    // ScaffoldMessenger.of(context).showSnackBar(
    //   SnackBar(
    //     content: Text(
    //       '图片已选择：${image.name}\n图片搜索功能开发中...',
    //       style: TextStyle(color: Colors.white),
    //     ),
    //     backgroundColor: Color(0xFFFF6B35),
    //     duration: Duration(seconds: 3),
    //     behavior: SnackBarBehavior.floating,
    //     shape: RoundedRectangleBorder(
    //       borderRadius: BorderRadius.circular(10.r),
    //     ),
    //   ),
    // );
  }

  // 显示错误信息
  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          message,
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.red,
        duration: Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.r),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.backHomeYellowGround,
        title: Text(
          'Search Products',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.bold,
            color: AppColors.textPrimary,
          ),
        ),
        leading: GestureDetector(
          onTap: () {
            JoyNavUtils().back();
          },
          child: Container(
            margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: AppColors.primaryVariant,
              size: 18.sp,
            ),
          ),
        ),
      ),
      body: BLocSearch(),
     );
  }

  Widget mainBuild(){
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.white,
            Colors.white,
          ],
        ),
      ),
      child: SafeArea(
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                  height: 100,
                  decoration: BoxDecoration(
                    color: AppColors.backHomeYellowGround,
                    borderRadius: BorderRadius.only(bottomRight: Radius.circular(30),bottomLeft: Radius.circular(30))
                  ),
                ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
                  height: 40.h,
                  decoration: BoxDecoration(

                    color: AppColors.backgroundSearch,
                    borderRadius: BorderRadius.circular(40.h),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          onChanged:(value){
                            debugPrint("value = $value");
                            if(value.trim().isEmpty){
                              searchWordList.clear();
                              setState(() {
                              });
                            }else{
                              loginBloc.add(GetJOYSearchKeyListEvent(context,value));
                            }
                          },
                          controller: _searchController,
                          autofocus: true,
                          textInputAction: TextInputAction.search,
                          cursorColor: Color(0xFFFF6B35),
                          onSubmitted: _performSearch,
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: AppColors.textPrimary,
                          ),
                          decoration: InputDecoration(
                            // focusedBorder: OutlineInputBorder(
                            //   borderSide: BorderSide(color: Color(0xFFFF6B35), width: 1),
                            //   borderRadius: BorderRadius.circular(8), // 与非聚焦保持一致
                            // ),
                            // enabledBorder: OutlineInputBorder(
                            //   borderSide: BorderSide(color: Colors.transparent, width: 1),
                            //   borderRadius: BorderRadius.circular(8), // 与非聚焦保持一致
                            // ),
                            hintText: 'Search within the app',
                            hintStyle: TextStyle(
                              color: AppColors.textHint,
                              fontSize: 16.sp,
                            ),
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 12.h,
                            ),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: _showImagePickerDialog,
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 8.w),
                          child: Icon(
                            Icons.camera_alt,
                            color: AppColors.primary,
                            size: 25.sp,
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => _performSearch(_searchController.text),
                        child: Container(
                          width: 36.w,
                          height: 36.w,
                          margin: EdgeInsets.only(right: 8.w),
                          decoration: BoxDecoration(
                            color: AppColors.primary,
                            borderRadius: BorderRadius.circular(20.r),
                          ),
                          child: Icon(
                            Icons.search,
                            color: Colors.white,
                            size: 18.sp,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // 搜索框区域


            // 搜索历史区域
            Expanded(
              child: showContain()
            ),
          ],
        ),
      ),
    );
  }

  Widget showContain(){
    if(searchWordList.isEmpty){
      return _searchHistory.isEmpty?_buildEmptyState():_buildSearchHistory();
    }else{
      return showListSearchView();
    }
  }

  Widget BLocSearch(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return mainBuild();
    }, create: (_) {
      loginBloc = JoyHomeBloc();

      return loginBloc;
    }, buildWhen: (previousState, state) {
      if(state is GetJOYSearchKeyListEventSuccess){
        searchWordList.clear();
        searchWordList.addAll(state.data??[]);
        return true;
      }
      if(state is PostUploadFileEventSuccess){
        String cloudImagePath = state.data;
        String url = ImageUrlUtil.getImageUrl(cloudImagePath);
        JoyNavUtils().to(JoySearchResultPage(searchword: url,seacrchImage: 1,));

        debugPrint("url == ${url}");

        return true;

      }
      if(state is PostUploadFileEventFailure){

        return true;

      }

      return false;
    });
  }

  Widget showListSearchView(){
    return Container(
      child: ListView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context,index){
          Map product = searchWordList[index]??{};
          String productName = product["productName"]??"";
          return InkWell(
            child: Container(
              padding: EdgeInsets.only(left: 10,right: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Icon(Icons.search,color: Colors.black,size: 20,),
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.only(left: 10,right: 10,top: 15,bottom: 15),
                          child: Text(
                            productName,
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    height: 0.5,
                    width: ScreenUtil().screenWidth,
                    color: Colors.grey[300],
                  )
                ],
              ),
            ),
            onTap: (){
              _addSearchRecord(productName);
              _performSearch(productName);
            },
          );
        },
        itemCount: searchWordList.length,
      ),
    );
  }

  // 空状态
  Widget _buildEmptyState() {
    return SingleChildScrollView(
      // 🔥 添加可滚动容器，防止键盘弹出时溢出
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 20.h),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min, // 🔥 使用 min 让内容自适应
          children: [
            // 插画容器
            Container(
              width: 120.w,
              height: 120.w,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    AppColors.primary.withOpacity(0.1),
                    AppColors.primary.withOpacity(0.05),
                  ],
                ),
                borderRadius: BorderRadius.circular(60.r),
              ),
              child: Icon(
                Icons.search_rounded,
                size: 60.sp,
                color: AppColors.primary.withOpacity(0.6),
              ),
            ),
            SizedBox(height: 32.h),
            Text(
              'Start Your Search Journey',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.bold,
                color: AppColors.textPrimary,
              ),
            ),
            SizedBox(height: 12.h),
            Text(
              'Enter product name in the search box above\nDiscover more exciting products',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16.sp,
                color: AppColors.textSecondary,
                height: 1.5,
              ),
            ),
            SizedBox(height: 32.h),
            // 热门搜索提示
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.trending_up,
                    size: 16.sp,
                    color: Color(0xFF666666),
                  ),
                  SizedBox(width: 8.w),
                  Flexible(
                    // 🔥 使用 Flexible 替代 Expanded，更灵活
                    child: Text(
                      'Try searching: shoes,clothing',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Color(0xFF666666),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 搜索历史列表
  Widget _buildSearchHistory() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 历史记录标题
          Container(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Container(
                      width: 4.w,
                      height: 20.h,
                      decoration: BoxDecoration(
                        color: Color(0xFFFF6B35),
                        borderRadius: BorderRadius.circular(2.r),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    Text(
                      'Search History',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: AppColors.textPrimary,
                      ),
                    ),
                  ],
                ),
                GestureDetector(
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                        title: Text(
                          'Clear Search History',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        content: Text(
                          'Are you sure you want to clear all search records?',
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white,
                          ),
                        ),
                        actions: [
                          TextButton(
                            onPressed: () => Navigator.pop(context),
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                color: AppColors.textSecondary,
                                fontSize: 16.sp,
                              ),
                            ),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context);
                              _clearAllSearchHistory();
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppColors.primary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                            ),
                            child: Text(
                              'Confirm',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                    decoration: BoxDecoration(
                      // color: AppColors.backgroundSecondary,
                      // borderRadius: BorderRadius.circular(16.r),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          height: 15,
                          width: 15,
                          child: Image.asset("images/icon_cleanHistory.png"),
                        )

                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 历史记录标签列表
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.only(bottom: 16.h),
              child: Align(
                alignment: Alignment.centerLeft, // 确保整体左对齐
                child: Wrap(
                  alignment: WrapAlignment.start, // 主轴左对齐
                  crossAxisAlignment: WrapCrossAlignment.start, // 交叉轴左对齐
                  runAlignment: WrapAlignment.start, // 行对齐方式为左对齐
                  spacing: 8.w, // 水平间距
                  runSpacing: 8.h, // 垂直间距
                  children: _searchHistory.map((query) {
                    return _buildHistoryChip(query);
                  }).toList(),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建历史记录标签
  Widget _buildHistoryChip(String query) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Color(0xFFFAFAFA),
        borderRadius: BorderRadius.circular(20.r),
        // border: Border.all(
        //   color: Color(0xFFFF6B35).withOpacity(0.3),
        //   width: 1,
        // ),
      ),
      child: Stack(
        children: [
          // 文本内容 - 可点击区域
          GestureDetector(
            onTap: () {
              _searchController.text = query;
              _performSearch(query);
            },
            child: Padding(
              padding: EdgeInsets.only(right: 20.w), // 为关闭按钮留出空间
              child: Text(
                query,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xFF9C9C9C),
                  fontWeight: FontWeight.w500,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          // 关闭按钮 - 独立点击区域
          Positioned(
            right: 0,
            top: 0,
            child: GestureDetector(
              onTap: () => _removeSearchRecord(query),
              child: Container(
                width: 16.w,
                height: 16.w,
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.close,
                  size: 10.sp,
                  color: AppColors.primary,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}